package cn.wubo.sqlparser;

import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.operators.relational.EqualsTo;
import net.sf.jsqlparser.expression.operators.relational.InExpression;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.schema.Table;
import net.sf.jsqlparser.statement.Statement;
import net.sf.jsqlparser.statement.insert.Insert;
import net.sf.jsqlparser.statement.select.Join;
import net.sf.jsqlparser.statement.select.PlainSelect;
import net.sf.jsqlparser.statement.select.Select;
import net.sf.jsqlparser.statement.select.SelectItem;
import net.sf.jsqlparser.statement.update.Update;
import net.sf.jsqlparser.util.TablesNamesFinder;

import java.util.List;

@Slf4j
public class JSQLParser {

    public static void parser(String sql) throws Exception {
        Statement statement = CCJSqlParserUtil.parse(sql);

        if (statement instanceof Select) {
            Select select = (Select) statement;
            PlainSelect plainSelect = (PlainSelect) select.getSelectBody();

            // 1.解析表名
            TablesNamesFinder tablesNamesFinder = new TablesNamesFinder(); // 创建表名发现者对象
            List<String> tableNameList = tablesNamesFinder.getTableList(statement); // 获取到表名列表
            tableNameList.forEach(e -> log.debug("to: table[{}]", e));

            // 2.解析查询元素=》 列，函数等
            List<SelectItem> selectItems = plainSelect.getSelectItems();
            selectItems.forEach(selectItem -> log.debug("to: selectItem[{}]", selectItem.toString())); // t1.a , t1.b

            Expression expression = plainSelect.getWhere();
            if (expression instanceof EqualsTo) {
                // 3.解析equalsTo
                EqualsTo equalsTo = (EqualsTo) expression;
                log.debug("to: [{}] EqualsTo [{}]", equalsTo.getLeftExpression().toString(), equalsTo.getRightExpression().toString());
            } else if (expression instanceof InExpression) {
                // 5.解析IN
                InExpression inExpression = (InExpression) expression;
                log.debug("to: [{}] InExpression [{}]", inExpression.getLeftExpression().toString(), inExpression.getRightItemsList().toString());
            }
            //...还有其他的一堆

            // 4.解析Join
            List<Join> joins = plainSelect.getJoins();
            joins.forEach(e -> log.debug("to: Join [{}]", e.getOnExpressions().toString()));
        } else if (statement instanceof Insert) {
            Insert insert = (Insert) statement;
            Table table = insert.getTable();
            List<Column> columns = insert.getColumns();
        } else if (statement instanceof Update) {
            Update update = (Update) statement;
            Table table = update.getTable();
            Expression expression = update.getWhere();
        }
    }
}
